package com.yunqiao.api.resolver;

import com.yunqiao.api.annotation.LoginUser;
import com.yunqiao.api.interceptor.AuthorizationInterceptor;
import com.yunqiao.api.utils.JwtUtils;
import com.yunqiao.service.api.UserService;
import com.yunqiao.service.api.entity.UserEntity;
import com.yunqiao.service.api.util.AccountEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 *
 * @author Crocutax
 * @email wangxw725@163.com
 * @date 2017-03-23 22:02
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserEntity.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        String object = (String) request.getAttribute(AuthorizationInterceptor.USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if (object == null) {
            return null;
        }
        //解决方案,在存入token时,存的就是[角色类型-用户ID]格式,这里截取,根据角色类型,查询不同的数据表,注入不同的LoginUser对象
        //1.单表账号
        UserEntity user = userService.getById(Long.valueOf(object));
        return user;

        //2.多表账号,放分隔符,为了根据角色去对应的表里查询
//        String token = String.valueOf(object);
//        String[] split = token.split(JwtUtils.TOKEN_SEPARATOR);
//        if (Integer.parseInt(split[0]) == AccountEnum.RoleType.USER.getValue()) {
//            UserEntity user = userService.getById((Long) object);
//            return user;
//        } else {
//            DriverEntity driverEntity = driverService.getById(split[1]);
//            return driverEntity;
//        }
    }
}
